package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

import static com.sky.entity.Orders.*;

/**
 * 定时任务类
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;
    /**
     * 判断有没有支付超时
     */
    @Scheduled(cron = "0 * * * * ? ")
    //@Scheduled(cron = "1/5 * * * * ?")
    public void processTimeOutTask(){
        log.info("定时处理超时订单{}", LocalDateTime.now());
        LocalDateTime payTime = LocalDateTime.now().minusMinutes(15);
        Integer pendingPayment = PENDING_PAYMENT;
        List<Orders> orders=orderMapper.getOrderByPayTime(pendingPayment,payTime);
        for(Orders order:orders){
            order.setCancelTime(LocalDateTime.now());
            order.setStatus(CANCELLED);
            order.setCancelReason("超时未支付");
            orderMapper.update(order);
        }
    }

    /**
     * 配送超时，自动完成订单
     */
    @Scheduled(cron = "0 0 1 * * ? ")
    //@Scheduled(cron = "0/5 * * * * ?")
    public void deliveryTimeOutTask(){
        log.info("定时处理处于派送中的订单{}", LocalDateTime.now());
        Integer deliveryInProgress = Orders.DELIVERY_IN_PROGRESS;
        List<Orders> orders=orderMapper.getOrderByDelivery(deliveryInProgress);
        for(Orders order:orders){
            order.setStatus(COMPLETED);
            orderMapper.update(order);
        }
    }



}
